#include <stdio.h>
#include <stdlib.h>

#include <QThread>
#include <QtGui>
#include <QDebug>

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    // create background image
    int imgW = 800, imgH = 600;
    m_img = new QImage(imgW, imgH, QImage::Format_RGB888);
    m_img->fill(QColor(255, 255, 255));

    // set window properties
    setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);

    // set focus to self
    setFocus();
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    QPainter painter;

    // 'C' - draw rectangles
    if( event->key() == Qt::Key_C ) {
        painter.begin(m_img);
        painter.setRenderHint(QPainter::Antialiasing, true);

        int width = 10;
        int height = 10;
        painter.setPen(QColor(128, 128, 128, 255));//设置画笔颜色
        for(int row = 0; row < 80; ++row) {
            for(int col = 0; col < 60; ++col) {
                int x1 = col * width;
                int y1 = row * height;
                painter.drawRect(x1, y1, width, height);
            }
        }

        painter.end();
    }

    // 'A' 清除背景图像，归为白色
    if( event->key() == Qt::Key_A ) {
        m_img->fill(QColor(255, 255, 255));
    }

    // 'q' - quit the program
    if( event->key() == Qt::Key_Q ) {
        this->close();
    }

    this->update();
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
}

void MainWindow::paintEvent(QPaintEvent * /* event */)
{
    QPainter    painter(this);

    // draw offline image to screen
    painter.drawImage(QPoint(0, 0), *m_img);
}
